<script setup>
import {useUserManagement} from "@/composables/useSysUser";
import {ElMessageBox} from "element-plus";
import {reactive, ref} from "vue";
import useSysRole from "@/composables/useSysRole.js";
import {useRouter} from 'vue-router'
import instance from "@/api/request.js";

const message = getCurrentInstance().proxy.$message;

// 使用 Hook
const {
    queryParams,
    userList,
    current,
    size,
    total,
    loading,
    search,
    reset,
    refresh,
    handleCurrentChange,
    handleSizeChange,
    fetchUserUpdate
} = useUserManagement();

let sysRole = useSysRole();
let roles = [];

onMounted(async () => {
    await sysRole.handleSizeChange(1000)
    roles = sysRole.roleList;
});

// UI 状态保留在组件
const selectedUsers = ref([]);

// 表格交互
const onSelectionChange = (selection) => {
    selectedUsers.value = selection;
};
// 模态框
const router = useRouter();
const dialogRef = ref();

const dialogVisibleModel = reactive({
    isVisible: false,
    option: null,
    title: '模态框',
    width: '800px',
    type: null,
    data: null
})

const submit = () => {
    dialogVisibleModel.isVisible = false;
    search();
}

const close = () => {
    dialogVisibleModel.isVisible = false;
    router.push("/user")
}
const closed = () => {
    dialogVisibleModel.width = '800px'
}
// 操作方法
const handleAdd = () => {

    router.push(`/user/add`).then(() => {
        Object.assign(dialogVisibleModel, {
            isVisible: true,
            type: 'insert',
            width: 600,
            option: router.currentRoute.value.meta.perms,
            title: router.currentRoute.value.meta.title,
        });
    })
};

const handleEdit = (row) => {

    router.push(`/user/edit/${row.username}`).then(() => {
        Object.assign(dialogVisibleModel, {
            isVisible: true,
            option: router.currentRoute.value.meta.perms,
            title: router.currentRoute.value.meta.title + ` - ${row.nickname}`,
            width: 600,
            type: 'update',
            data: row
        });
    })
};

const handleDelete = (row) => {
    ElMessageBox.confirm("确认删除当前用户吗？", {
        title: '注意',
        type: 'warning',
    }).then(res => {
        instance.put("/system/user/del_flag_update", {
            id: row.id
        }).then(response => {
            console.log(response.data)
            refresh();
        })
    })
};

const handleBatchDelete = () => {
    if (selectedUsers.value.length === 0) return;
    const ids = selectedUsers.value.map((u) => u.id);
    ElMessageBox.confirm(`即将删除 ${ids.length} 个 用户`, {
        type: 'warning',
        title: '注意'
    }).then(() => {
        instance.put("/system/user/del_flag_batch_update", ids).then(response => {
            selectedUsers.value = [];
            message.success(`批量删除了 ${ids.length} 个用户`);
            refresh();
        })

    });
};

const handleNodeClick = (node) => {
}
const treeRef = ref();
const handleNodeCheckChange = (data, checked, indeterminate) => {
    let checkedNodes = treeRef.value.getCheckedNodes();
    queryParams.roleCodes = checkedNodes.map(node => node.roleCode)
    search();
}
const handleDetail = (row) => {
    router.push(`/user/${row.nickname}`).then(() => {
        Object.assign(dialogVisibleModel, {
            isVisible: true,
            option: router.currentRoute.value.meta.perms,
            title: router.currentRoute.value.meta.title + ` - ${row.nickname}`,
            width: 1314,
            type: 'detail',
            data: row
        });
    })
}
onMounted(() => {
    if (typeof search === 'function') search();
})
const statusToBoolean = (status) => status === 1;
const booleanToStatus = (boolean, row) => {
    row.status = boolean ? 1 : 0;
};
const updateStatus = (row) => {
    fetchUserUpdate(row).then(res => {
        ElMessage.success(res.message || '修改状态成功')
    })
};
const openColumnSetting = () => {
    ElMessageBox.alert("列设置功能待实现", "列设置", {
        confirmButtonText: "确定",
    });
};

const tableRef = ref();
const selectionVisible = ref(false)
const inSelectionVisible = () => {
    selectionVisible.value = !selectionVisible.value;
    if (!selectionVisible.value) {
        selectedUsers.value = [];
        // 用于多选表格，清空用户的选择
        tableRef.value.clearSelection()
    }
}
</script>

<template>
    <div class="user-management p-4 bg-white rounded-lg shadow-sm border border-gray-200">
        <!-- Header -->
        <h2 class="text-lg font-medium pb-2">用户管理</h2>

        <!-- 查询表单 -->
        <el-form :model="queryParams" class="mb-4 flex flex-wrap items-end gap-4" inline label-suffix=":">
            <el-form-item label="用户名/昵称" prop="username">
                <el-input v-model="queryParams.username" placeholder="用户名/昵称" style="width: 180px"/>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-select v-model="queryParams.gender" clearable placeholder="全部" style="width: 120px">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                    <el-option label="保密" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" clearable placeholder="全部" style="width: 120px">
                    <el-option :value="1" label="启动"></el-option>
                    <el-option :value="0" label="停用"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" type="primary" @click="search">搜索</el-button>
                <el-button icon="RefreshRight" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 工具栏 -->
        <div class="flex flex-wrap justify-between items-center pb-2 gap-2">
            <!-- 左侧操作 -->
            <div class="flex flex-wrap gap-2">
                <el-button
                    icon="Plus"
                    plain
                    type="primary"
                    @click="handleAdd" v-permission:user:insert
                >
                    新增
                </el-button>
                <el-button
                    v-if="selectionVisible"
                    :disabled="selectedUsers.length === 0"
                    icon="Delete"
                    plain
                    type="danger"
                    @click="handleBatchDelete"
                    v-permission:user:delete
                >
                    批量删除
                </el-button>
                <el-button :color="'#ccc'" :icon="!selectionVisible ? 'Finished' : 'CloseBold'" v-permission:user:delete
                           :style="{color: selectionVisible ? '#fff': '#111'}" :type="selectionVisible ? 'info': 'text'"
                           @click="inSelectionVisible">{{ !selectionVisible ? '批量管理' : '完成' }}
                </el-button>
            </div>
            <div class="flex flex-wrap gap-2">
                <el-button icon="Refresh" @click="refresh">刷新</el-button>
            </div>
        </div>

        <!-- 表格容器 -->
        <div class="border border-gray-200 overflow-hidden flex flex-row">
            <div style="width: 200px">
                <el-tree
                    ref="treeRef"
                    :data="roles"
                    :props="{label: 'roleName', children: 'rolePerms'}"
                    node-key="roleCode"
                    show-checkbox
                    @node-click.self="handleNodeClick"
                    @check-change="handleNodeCheckChange"
                >

                </el-tree>
            </div>
            <!-- 主表格区 -->
            <div class="flex-1" style="width: calc(100% - 200px)">
                <el-table
                    ref="tableRef"
                    v-loading="loading"
                    :data="userList"
                    border
                    height="520"
                    highlight-current-row
                    @selection-change="onSelectionChange"
                >
                    <el-table-column v-if="selectionVisible" type="selection" width="50"/>
                    <el-table-column align="center" label="序号" prop="index" width="80">
                        <template #default="{ $index }">
                            {{ $index + 1 + size * (current - 1) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="用户名" prop="username" sortable width="120">
                        <template #default="{row}">
                            <el-button type="text" @click="handleDetail({...row})" v-permission:user:detail>{{ row.username }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="昵称" prop="nickname" width="100"/>

                    <el-table-column label="状态" prop="status" sortable width="120">
                        <template #default="{ row }">
                            <el-switch
                                v-model="row.status"
                                :active-color="'#13ce66'"
                                :active-value="1"
                                :inactive-color="'#ff4949'"
                                :inactive-value="0"
                                active-text="启用"
                                inactive-text="停用"
                                inline-prompt
                                @change="updateStatus(row)" v-permission:user:update
                            />

                        </template>
                    </el-table-column>
                    <el-table-column label="联系电话" prop="phone"/>

                    <el-table-column label="创建时间" prop="createTime" sortable/>
                    <el-table-column fixed="right" label="操作" width="240">
                        <template #default="{ row }">
                            <el-button plain size="small" type="info" @click.stop="handleDetail({...row})" v-permission:user:detail="row">详细
                            </el-button>
                            <el-button size="small" type="primary" @click.stop="handleEdit(row)" v-permission:user:update="row">编辑</el-button>
                            <el-popconfirm title="确定删除？" @confirm="handleDelete(row)">
                                <template #reference>
                                    <el-button size="small" type="danger" v-permission:user:delete="row">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="p-4 border-t border-gray-200 flex justify-end">
                    <el-pagination
                        :current-page="current"
                        :page-size="size"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="total"
                        layout="total, prev, pager, next, sizes, jumper"
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </div>

            <el-drawer v-if="dialogVisibleModel.type==='detail'" v-model="dialogVisibleModel.isVisible"
                       :size="dialogVisibleModel?.width" :title="dialogVisibleModel?.title" @close="close"
                       destroy-on-close
            >
                <router-view v-if="dialogVisibleModel?.isVisible" v-slot="{Component}">
                    <component :is="Component"
                               :data="dialogVisibleModel?.data"
                               @cancel="()=>{dialogVisibleModel.isVisible= false}"
                               @submit="submit"/>
                </router-view>
            </el-drawer>
            <el-dialog v-else ref="dialogRef" v-model="dialogVisibleModel.isVisible"
                       :lock-scroll="true" :title="dialogVisibleModel?.title"
                       :width="dialogVisibleModel?.width" @close="close">
                <router-view v-if="dialogVisibleModel?.isVisible" v-slot="{Component}">
                    <component :is="Component"
                               :data="dialogVisibleModel?.data"
                               @cancel="()=>{dialogVisibleModel.isVisible= false}"
                               @submit="submit"/>
                </router-view>
            </el-dialog>

        </div>
    </div>
</template>

<style scoped>
.user-management :deep(.el-table__row:hover) {
    cursor: pointer;
}
</style>
